<?php

namespace App\Repositories\User;

use  App\Repositories\Repository;
use App\Models\User;
use Illuminate\Support\Facades\Request;
use App\Events\User\UserRegister;

class UserRepository extends Repository {

	protected $order = array('register_time', 'desc');

	public function __construct(User $user) {
		$this->model = $user;
	}

	/**
	 * 构造搜索条件
	 * @param $condition
	 * @return array
	 */
	public function SearchCondition($condition) {
		$SearchCondition = array();

		if ($condition['keyword_type'] && $condition['keywords']) {
			$SearchCondition[$condition['keyword_type']] = array('like', '%' . $condition['keywords'] . '%');
		}

		return $SearchCondition;
	}

	/**
	 * 添加用户
	 * @param array  $data
	 * @param string $type
	 * @return mixed
	 */
	public function create(array $data, $type = 'mobile') {
		$user = '';
		if ($type == 'mobile') {
			$user = $this->model->create([
				'mobile'        => $data['mobile'],
				'name'          => $data['name'],
				'password'      => bcrypt($data['password']),
				'register_time' => time(),
				'register_ip'   => Request::getClientIp()
			]);
		}

		if($user){
			//触发用户注册事件
			event(new UserRegister($user));
		}
		return $user;
	}

	/**
	 * 设置角色
	 * @param       $userId
	 * @param array $roleIds
	 * @return mixed
	 */
	public function assignRole($userId,array $roleIds) {
		$user = $this->find($userId);
		return $user->roles()->sync($roleIds);
	}
}
